﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DAO
{
    public class BUDDataAccess : Connection
    {
        public bool exists(DTO.GlobalParametersInfo info, ref string sErr)
        {
            InitConnect();
            InitCommand("SELECT TOP 1 * FROM GlobalParameters", System.Data.CommandType.Text);

            DataTable list = new DataTable();
            try { list = executeSelect(); }
            catch (Exception ex) { sErr = ex.Message; }

            if (list.Rows.Count > 0) return true;
            return false;
        }

        public string update(DTO.GlobalParametersInfo info)
        {
            string sErr = "";
            openConnection();

            InitCommand("UPDATE GlobalParameters SET DocFolder = @DocFolder, PeriodFrom = @PeriodFrom, PeriodTo = @PeriodTo, Tolerance = @Tolerance", System.Data.CommandType.Text);
            AddParameter(DTO.GlobalParametersInfo.Field.DocFolder.ToString(), info.DocFolder);
            AddParameter(DTO.GlobalParametersInfo.Field.PeriodFrom.ToString(), info.PeriodFrom);
            AddParameter(DTO.GlobalParametersInfo.Field.PeriodTo.ToString(), info.PeriodTo);
            AddParameter(DTO.GlobalParametersInfo.Field.Tolerance.ToString(), info.Tolerance);

            try { executeNonQuery(); }
            catch (Exception ex) { sErr = ex.Message; }

            finally {closeConnection();}
            return sErr;
        }

        public void add(DTO.GlobalParametersInfo info, ref string sErr)
        {
            openConnection();

            InitCommand("INSERT INTO GlobalParameters(DocFolder,PeriodFrom,PeriodTo,Tolerance) VALUES(@DocFolder,@PeriodFrom,@PeriodTo,@Tolerance)", System.Data.CommandType.Text);
            AddParameter(DTO.GlobalParametersInfo.Field.DocFolder.ToString(), info.DocFolder);
            AddParameter(DTO.GlobalParametersInfo.Field.PeriodFrom.ToString(), info.PeriodFrom);
            AddParameter(DTO.GlobalParametersInfo.Field.PeriodTo.ToString(), info.PeriodTo);
            AddParameter(DTO.GlobalParametersInfo.Field.Tolerance.ToString(), info.Tolerance);

            try { executeNonQuery(); }
            catch (Exception ex) { sErr = ex.Message; }

            finally {closeConnection();}
        }

        public DTO.GlobalParametersInfo get(ref string sErr)
        {
            DTO.GlobalParametersInfo ret = null;
            InitConnect();
            InitCommand("SELECT TOP 1 ID,DocFolder,PeriodFrom,PeriodTo,Tolerance FROM GlobalParameters", System.Data.CommandType.Text);

            DataTable list = new DataTable();

            try { list = executeSelect(); }
            catch (Exception ex) { sErr = ex.Message; }

            if (list.Rows.Count > 0) ret = new DTO.GlobalParametersInfo(list.Rows[0]);

            return ret;
        }
    }
}
